/*
 * Copyright 2009 Johnson Consulting Services
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * 
 */
package com.johnsoncs.gwt.widgets.samples.client;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.johnsoncs.gwt.application.client.model.Data;
import com.johnsoncs.gwt.application.client.model.Model;
import com.johnsoncs.gwt.application.client.model.Data.Property;

/**
 * @author wilj
 *
 */
public class ModelTree extends Composite {
	final Tree tree = new Tree();
	final Model model;

	public ModelTree(final Model model) {
		this.model = model;
		super.initWidget(tree);
	}

	private void addChildren(final Data branch, final TreeItem parent) {
		for (final Property p : branch) {
			TreeItem item;
			if (p.getValueType().equals(Data.class)) {
				item = parent.addItem(p.getKey().toString() + " = Data");
			} else {
				item = parent.addItem(p.getKey().toString() + " = " + p.getValue().toString());
			}
			if (p.getValueType().equals(Data.class)) {
				final Data d = p.getValue();
				if (d != null) {
					addChildren(d, item);
				}
			}
			item.setState(true);
		}
	}

	@Override
	protected void onLoad() {
		refresh();
	}

	public void refresh() {
		tree.clear();
		final TreeItem root = tree.addItem("Model");
		addChildren(model.getRoot(), root);
		root.setState(true);
	}

}
